<template>
  <section>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">
      <el-row>
        <el-col :span="20">
          <el-form-item label="活动标题" prop="title">
            <el-input v-model="dataForm.title" placeholder="活动标题"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="原价" prop="originalPrice">
            <el-input v-model="dataForm.originalPrice" placeholder="原价"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="抢购价" prop="buyingPrice">
            <el-input v-model="dataForm.buyingPrice" placeholder="抢购价"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="门店名称" prop="storeId">
            <el-select v-model="dataForm.storeId" placeholder="请选择门店名称" style="width:100%" @change="changeStoreList">
              <el-option v-for="item in StoreList" :key="item.id" :label="item.storeName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="项目名称" prop="itemsId">
            <el-select v-model="dataForm.itemsId" placeholder="请选择项目名称" style="width:100%">
              <el-option v-for="item in ItemsList" :key="item.id" :label="item.itemName" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="活动开始日期" prop="startDate">
            <el-date-picker v-model="dataForm.startDate" type="datetime" placeholder="选择日期时间" default-time="12:00:00" value-format="yyyy-MM-dd HH:mm:ss" style="width:100%"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="活动结束日期" prop="endDate">
            <el-date-picker v-model="dataForm.endDate" type="datetime" placeholder="选择日期时间" default-time="12:00:00" value-format="yyyy-MM-dd HH:mm:ss" style="width:100%"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="活动描述" prop="introduction">
            <el-input type="textarea" :rows="2" placeholder="请输入活动描述" v-model="dataForm.introduction"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="活动规则" prop="rules">
            <el-input type="textarea" :rows="2" placeholder="请输入活动规则" v-model="dataForm.rules"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="活动状态" prop="status">
            <el-switch v-model="dataForm.status" active-color="#13ce66" inactive-color="#ff4949" :active-value="0" :inactive-value="1"></el-switch>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="分享标题" prop="shareTitle">
            <el-input type="text" placeholder="请输入活动规则" v-model="dataForm.shareTitle"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="分享描述" prop="shareDesc">
            <el-input type="text" placeholder="请输入活动规则" v-model="dataForm.shareDesc"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="分享图标" prop="shareIcon">
            <el-upload class="upload-demo" :action="upload.url+'/hd-api/upload/file'" :headers="headers" :on-remove="handleRemove" :file-list="dataForm.fileListfx" :on-success="handlefxSuccess" list-type="picture-card">
              <el-button size="small" type="text">分享图标上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="轮播图" prop="banner">
            <el-upload class="upload-demo" :action="upload.url+'/hd-api/upload/file'" :headers="headers" :on-remove="handleRemove" :file-list="dataForm.fileList" :on-success="handleSuccess" list-type="picture-card">
              <el-button size="small" type="text">轮播图上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="20">
          <el-form-item label="视频" prop="details">
            <el-upload class="avatar-uploader" :action="upload.url+'/hd-api/upload/file'" :headers="headers" :on-progress="uploadVideoProcess" :on-success="handleVideoSuccess" :before-upload="beforeUploadVideo" :show-file-list="false">
              <video v-if="dataForm.video && !videoFlag" :src="upload.url + dataForm.video" class="avatar video-avatar" controls="controls">
                您的浏览器不支持视频播放
              </video>
              <el-button v-else size="small" type="text" class="uploadVideo">视频上传</el-button>
              <div slot="tip" class="el-upload__tip">最多可以上传1个视频，建议大小50M，推荐格式mp4</div>
              <el-progress v-if="videoFlag == true" type="circle" :percentage="videoUploadPercent" style="margin-top:7px;"></el-progress>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="详情" prop="details">
            <quill-editor v-model="dataForm.details" ref="myQuillEditor" :options="editorOption"></quill-editor>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <span slot="footer" align-items="center">
      <el-button @click="historyCancel">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </section>
</template>

<script>
  import Vue from 'vue'
  import ueditor from 'ueditor'
  // 工具栏配置
  const toolbarOptions = [
    ["bold", "italic", "underline", "strike"], // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
    ["blockquote", "code-block"], // 引用  代码块-----['blockquote', 'code-block']
    [{ header: 1 }, { header: 2 }], // 1、2 级标题-----[{ header: 1 }, { header: 2 }]
    [{ list: "ordered" }, { list: "bullet" }], // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
    [{ script: "sub" }, { script: "super" }], // 上标/下标-----[{ script: 'sub' }, { script: 'super' }]
    [{ indent: "-1" }, { indent: "+1" }], // 缩进-----[{ indent: '-1' }, { indent: '+1' }]
    [{ direction: "rtl" }], // 文本方向-----[{'direction': 'rtl'}]
    [{ size: ["small", false, "large", "huge"] }], // 字体大小-----[{ size: ['small', false, 'large', 'huge'] }]
    [{ header: [1, 2, 3, 4, 5, 6, false] }], // 标题-----[{ header: [1, 2, 3, 4, 5, 6, false] }]
    [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色-----[{ color: [] }, { background: [] }]
    [{ font: [] }], // 字体种类-----[{ font: [] }]
    [{ align: [] }], // 对齐方式-----[{ align: [] }]
    ["clean"], // 清除文本格式-----['clean']
    ["image", "video"] // 链接、图片、视频-----['link', 'image', 'video']
  ];
  export default {
    data() {
      return {
        upload: {
          url: 'https://shanxihongdi.com'
        },
        content: '',
        editorOption: {
          modules: {
            toolbar: toolbarOptions
          },
          theme: "snow",
          placeholder: "请输入详情"
        },
        headers: {
          token: Vue.cookie.get('token')
        },
        visible: false,
        StoreList: [],
        ItemsList: [],
        videoList: [],
        dataForm: {
          id: 0,
          title: '',
          originalPrice: '',
          buyingPrice: '',
          banner: '',
          startDate: '',
          endDate: '',
          introduction: '',
          rules: '',
          details: '',
          status: '',
          storeId: '',
          shareIcon: '',
          shareDesc: '',
          shareTitle: '',
          itemsId: '',
          fileList: [],
          fileListfx: [],
          createTime: '',
          video: undefined
        },
        options: [],
        dataRule: {
          title: [{
            required: true,
            message: '活动标题不能为空',
            trigger: 'blur'
          }],
          originalPrice: [{
            required: true,
            message: '原价不能为空',
            trigger: 'blur'
          }],
          buyingPrice: [{
            required: true,
            message: '抢购价不能为空',
            trigger: 'blur'
          }],
          banner: [{
            required: true,
            message: '轮播图不能为空',
            trigger: 'blur'
          }],
          startDate: [{
            required: true,
            message: '活动开始日期不能为空',
            trigger: 'blur'
          }],
          endDate: [{
            required: true,
            message: '活动结束日期不能为空',
            trigger: 'blur'
          }],
          introduction: [{
            required: true,
            message: '活动描述不能为空',
            trigger: 'blur'
          }],
          rules: [{
            required: true,
            message: '活动规则不能为空',
            trigger: 'blur'
          }],
          details: [{
            required: true,
            message: '详情不能为空',
            trigger: 'blur'
          }],
          storeId: [{
            required: true,
            message: '门店名称不能为空',
            trigger: 'blur'
          }],
          itemsId: [{
            required: true,
            message: '项目名称不能为空',
            trigger: 'blur'
          }],
          createTime: [{
            required: true,
            message: '创建时间不能为空',
            trigger: 'blur'
          }]
        },
        videoFlag: false,
        //是否显示进度条
        videoUploadPercent: "",
        //进度条的进度，
        isShowUploadVideo: false,
        //显示上传按钮
        videoForm: {
          showVideoPath: ''
        }
      }
    },
    computed: {
      //当前富文本实例
      editor() {
        return this.$refs.myQuillEditor.quill;
      }
    },
    mounted() {
      this.getStoreList()
      // if (this.$route.query.id) {
      //   this.dataForm.id = this.$route.query.id;
      //   this.$refs['dataForm'].resetFields();
      //   this.init(this.$route.query.id);
      // }
    },
    methods: {
      // 获取门店名称 ID
      async getStoreList() {
        let {
          data
        } = await this.$http({
          url: this.$http.adornUrl(`/activity/store/listStore`),
          method: 'get',
          params: this.$http.adornParams()
        })
        if (data && data.code === 0) {
          this.StoreList = data.StoreList
        }
      },
      // 获取项目名称 ID
      async changeStoreList(row) {
        let {
          data
        } = await this.$http({
          url: this.$http.adornUrl(`/activity/items/listItems/${row}`),
          method: 'get',
          params: this.$http.adornParams()
        })
        if (data && data.code === 0) {
          this.ItemsList = data.itemsList
        }
      },
      async init(id) {
        this.dataForm.id = id || 0
        this.$refs['dataForm'] && this.$refs['dataForm'].resetFields()
        let { data } = await this.$http({
          url: this.$http.adornUrl(`/activity/activity/info/${this.dataForm.id}`),
          method: 'get',
          params: this.$http.adornParams()
        })
        if (data && data.code === 0) {
          if (!data.activity) {
            this.dataForm.fileList = this.dataForm.fileListfx = [];
            return;
          };
          this.changeStoreList(data.activity.storeId)
          this.dataForm.fileList = [{
            name: data.activity.banner.split('/').splice(-1)[0],
            url: this.upload.url + data.activity.banner
          }]
          this.dataForm.fileListfx = [{
            name: data.activity.shareIcon.split('/').splice(-1)[0],
            url: this.upload.url + data.activity.shareIcon
          }]
          this.dataForm.banner = data.activity.banner
          this.dataForm.buyingPrice = data.activity.buyingPrice
          this.dataForm.details = data.activity.details
          this.dataForm.endDate = data.activity.endDate
          this.dataForm.introduction = data.activity.introduction
          this.dataForm.itemsId = data.activity.itemsId
          this.dataForm.originalPrice = data.activity.originalPrice
          this.dataForm.status = data.activity.status
          this.dataForm.rules = data.activity.rules
          this.dataForm.startDate = data.activity.startDate
          this.dataForm.storeId = data.activity.storeId
          this.dataForm.shareIcon = data.activity.shareIcon
          this.dataForm.shareDesc = data.activity.shareDesc
          this.dataForm.shareTitle = data.activity.shareTitle
          this.dataForm.title = data.activity.title
          this.dataForm.video = data.activity.video
        }
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs['dataForm'].validate(async (valid) => {
          if (valid) {
            let { data } = await this.$http({
              url: this.$http.adornUrl(`/activity/activity/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'title': this.dataForm.title,
                'originalPrice': this.dataForm.originalPrice,
                'buyingPrice': this.dataForm.buyingPrice,
                'banner': this.dataForm.banner,
                'startDate': this.dataForm.startDate,
                'endDate': this.dataForm.endDate,
                'introduction': this.dataForm.introduction,
                'rules': this.dataForm.rules,
                'details': this.dataForm.details,
                'status': this.dataForm.status,
                'storeId': this.dataForm.storeId,
                'itemsId': this.dataForm.itemsId,
                'createTime': this.dataForm.createTime,
                'video': this.dataForm.video,
                'shareIcon': this.dataForm.shareIcon,
                'shareDesc': this.dataForm.shareDesc,
                'shareTitle': this.dataForm.shareTitle,
                'storeName': this.StoreList.filter(v => v.id === this.dataForm.storeId)[0].storeName,
                'itemName': this.ItemsList.filter(v => v.id === this.dataForm.itemsId)[0].itemName,
              })
            })
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                  this.historyCancel()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          }
        })
      },
      handleRemove(file, fileList) {
        console.log(file, fileList)
      },
      handleSuccess(file) {
        if (file.code === 0) {
          this.dataForm.banner = file.msg
        }
      },
      handlefxSuccess(file) {
        if (file.code === 0) {
          this.dataForm.shareIcon = file.msg
        }
      },
      historyCancel() {
        window.history.go(-1)
      },
      //上传前回调
      beforeUploadVideo(file) {
        var fileSize = file.size / 1024 / 1024 < 50;
        if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb', 'video/mov'].indexOf(file.type) == -1) {
          this.$message.error("请上传正确的视频格式");
          return false;
        }
        if (!fileSize) {
          this.$message.error("视频大小不能超过50MB");
          return false;
        }
        this.isShowUploadVideo = false;
      },
      //进度条
      uploadVideoProcess(event, file, fileList) {
        this.videoFlag = true;
        this.videoUploadPercent = file.percentage.toFixed(0) * 1;
      },
      //上传成功回调
      handleVideoSuccess(res, file) {
        this.isShowUploadVideo = true;
        this.videoFlag = false;
        this.videoUploadPercent = 0;
        //后台上传地址
        debugger
        if (res.code == 0) {
          this.dataForm.video = res.msg;
        } else {
          this.$message.error(res.msg);
        }
      }
    },
    watch: {
      '$route.query': {
        handler(newVal, oldVal) {
          if (newVal.id) {
            this.$route.meta.title = '编辑活动';
            this.dataForm.id = newVal.id;
            // this.$refs['dataForm'].resetFields();
            this.init(newVal.id);
          } else {
            this.$route.meta.title = '新建活动';
            this.init();
          }
          // console.log(this.$route, this.$route.meta.title);
        },
        immediate: true,
        deep: true
      }
    }
  }
</script>

<style lang="scss" scoped>
  .upload-demo {
    .el-upload--picture-card {
      background-color: #fbfdff;
      border: 1px dashed #c0ccda;
      border-radius: 6px;
      box-sizing: border-box;
      width: 60px;
      height: 60px;
      display: inline-flex;
      align-items: center;
      line-height: normal;
    }

    .el-upload-list--picture-card {
      .el-upload-list__item {
        width: 60px;
        height: 60px;
      }
    }

    .ql-container {
      min-height: 100px;
    }
  }
</style>
